import { render } from 'ejs'
import { parse } from '@vue/compiler-sfc'
export default ({ title }) => {
  console.log(title)
  return {
    name: 'vite-plugin-setup-extend',
    enforce: 'pre', //“pre” vite 核心插件之前执行
    //本篇介绍实现两个功能：1.index.html 自动注入title; 2. 扩展 script-setup 设置组件名name
    async transformIndexHtml(html) {
      const result = await render(html, { title })
      return result
    },

    //2. 扩展 script-setup 设置组件名name xxx.vue
    transform(code, id) {
      if (/\.vue$/.test(id)) {
        //script-setup中有这个name //defin
        const { descriptor } = parse(code)
        //1.是否是setup-script
        if (!descriptor?.scriptSetup?.setup) {
          return null
        }

        const { lang, name } = descriptor.scriptSetup?.attrs || {}
        const dillStr = headString(lang, name)
        code += dillStr
        return code
      }
    }
  }
}
//设置组件名name，需要插入的脚本
const headString = (lang, name) => {
  return `<script ${lang ? `lang="${lang}"` : ''}>
import { defineComponent } from 'vue'
export default defineComponent({
  ${name ? `name: "${name}",` : ''}
})
</script>\n`
}
